package utn.bi.xml;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;

// Xalan Parser (2.9.1):   http://xerces.apache.org/xerces2-j/index.html
//import org.apache.xml.serializer.OutputPropertiesFactory;
//import org.apache.xml.serializer.Serializer;
//import org.apache.xml.serializer.SerializerFactory;
import org.apache.xml.serializer.*;
import org.w3c.dom.Document;

public class XMLHandler {

	/**
	 * Create a new document.
	 * @return a new blank document.
	 * @author Maximiliano Abrutsky.
	 */
	public static Document getBlankDocument()	
	{
		Document newDoc = null;
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			newDoc = builder.newDocument();
		}
		// Parser with default options can't be built
		catch (ParserConfigurationException e) {			
			throw new RuntimeException(e);
		}

		return newDoc;
	}
	

	/**
	 * Persist a DOM Document to a file in a specified path.
	 * <br/>The default encoding is UTF-8.
	 * @param sourceDoc The document to be saved on file system.
	 * @param xmlSourceFile The absolute path with the file name including his extension.
	 * @throws IOException When the path is inaccessible.
	 * @author Maximiliano Abrutsky.
	 */
	public static void saveDocument(Document sourceDoc, String xmlSourceFile) throws IOException
	{
		String defaultMethodProperties = "xml";
		String encoding = "UTF-8";
		final java.io.FileOutputStream output = new java.io.FileOutputStream(xmlSourceFile);
		
		java.util.Properties outputProps = OutputPropertiesFactory.getDefaultMethodProperties(defaultMethodProperties);
		outputProps.put(OutputKeys.ENCODING, encoding);
		Serializer serializer = SerializerFactory.getSerializer(outputProps); 
		serializer.setOutputStream(output);
		serializer.asDOMSerializer().serialize(sourceDoc);
		
		output.flush();
		output.close();
	}
}
